import customViewService from '../apis/customview';
import {Message} from 'iview';

const SET_CUSTOM_VIEW = 'SET_CUSTOM_VIEW';

const state = {
    userCustomViewRepository: {}
};
const getters = {};
const actions = {
    getCustomView({commit, state}, payload) {
        return customViewService.getCustomViewApi(payload.formId).then(response => {
            if (response.data.code !== 0) {
                Message.error(response.data.msg);
                throw new Error(response.data.msg);
            } else {
                return response.data.data;
            }
        }).then(data => {
            commit(SET_CUSTOM_VIEW, {
                formId: payload.formId,
                list: data
            });
            if (payload.success !== undefined) {
                payload.success();
            }
        }).catch(err => {

        });
    },
    setCustomView({commit, state}, payload) {
        return customViewService.setCustomViewApi({formId: payload.formId, list: payload.list}).then(res => {
            if (res.data.code !== 0) {
                Message.error(res.data.msg);
                throw new Error(res.data.msg);
            } else {
                return res.data.data;
            }
        }).then(data => {
            commit(SET_CUSTOM_VIEW, {
                formId: payload.formId,
                list: data
            });
            if (payload.success !== undefined) {
                payload.success();
            }
        }).catch(err => {
            console.log(err);
        });
    },
    resizeCustomView({commit, state}, payload) {
        return customViewService.resizeCustomViewApi({id: payload.id, width: payload.width}).then(res => {
            if (res.data.code !== 0) {
                Message.error(res.data.msg);
                throw new Error(res.data.msg);
            } else {
                return res.data.data;
            }
        }).then(data => {
            commit(SET_CUSTOM_VIEW, {
                formId: payload.formId,
                list: data
            });
            if (payload.success !== undefined) {
                payload.success();
            }
        }).catch(err => {
            console.log(err);
        });
    }
};
const mutations = {
    [SET_CUSTOM_VIEW](state, {formId, list}) {
        state.userCustomViewRepository[formId] = list;
    }
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};